package com.example.bloodbankapplication.fragment;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.example.bloodbankapplication.R;
import com.example.bloodbankapplication.database.DonorStorage;
import com.example.bloodbankapplication.entity.PersonInformationModel;
import com.example.bloodbankapplication.service.BloodBankService;

public class ListOfDonors  extends BaseFragment implements OnItemClickListener{
	private ArrayList<PersonInformationModel> list;
	private ListView listview;
	private String instanceUrl;
	private String accessToken;
	private final String ACTION ="ListOfDonors";
	private MyReceiver mReceiver;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.donorslist, null);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		MenuItem addAccount = menu.add("Logout");
		MenuItemCompat.setShowAsAction(addAccount, MenuItemCompat.SHOW_AS_ACTION_ALWAYS );
		addAccount.setIcon(R.drawable.logout); 
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		 if(item.getTitle().equals("Logout")){
			 logout();
		 }
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		
		mReceiver = new MyReceiver();
		
		listview = (ListView) getView().findViewById(R.id.listview);
		listview.setOnItemClickListener(this);
		
		instanceUrl = mPreferance.getString("Instance", "");
		accessToken = mPreferance.getString("Access", "");
		
		
		if(!getConnectivity())
		{
			showPopUp(getActivity(), getResources().getString(R.string.nonetwork));
		}else{
		String retriveDonorList = instanceUrl+"/services/data/v26.0/query/?q=select+Name,Age__c,BloodGroup__c,City__c,Email__c,Gender__c,LastName__c,MiddleName__c,Phone__c,State__c,ZipCode__c+from+DonarRegistration__c";
		
		Log.i("NCS","URL is :"+retriveDonorList);
		
		Intent intent = new Intent(getActivity(),BloodBankService.class);
		intent.putExtra("Action", ACTION);
		intent.putExtra("URL", retriveDonorList);
		intent.putExtra("AccessToken", accessToken);
		intent.putExtra("Screen", "ListOfDonors");
		intent.putExtra("Type", "");
		startProgressDialog();
		getActivity().startService(intent);
		}
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getActivity().registerReceiver(mReceiver, new IntentFilter(ACTION));
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		getActivity().unregisterReceiver(mReceiver);
		super.onDestroy();
	}
	
	class MyReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			
			Log.i("NCS","List of Donors response"+arg1.getStringExtra("Key"));
			
			list = new ArrayList<PersonInformationModel>();
			
			try{
			JSONObject jObject = new JSONObject(arg1.getStringExtra("Key"));
			JSONArray donors = jObject.getJSONArray("records");
			int count = donors.length();
			
			for(int i=0;i<count;i++){
				JSONObject persons = donors.getJSONObject(i);
				
				PersonInformationModel model = new PersonInformationModel();
				model.setName(persons.getString("Name"));
				model.setPhno(persons.getString("Phone__c"));
				model.setBloodGroup(persons.getString("BloodGroup__c"));
				model.setEmail(persons.getString("Email__c"));
				model.setLastname(persons.getString("LastName__c"));
				model.setState(persons.getString("City__c"));
				model.setCity(persons.getString("State__c"));
				
				list.add(model);
				
			}
			
			
			stopProgressDialog();
			Collections.sort(list, new ListComparator());
			listview.setAdapter(new DataDisplayAdapter(list));
			
			
			
			
			}
			catch(Exception ex){
				
			}
			
			
			
		}
		
	}
	
	class ListComparator implements Comparator<PersonInformationModel>,Serializable
	{
	public int compare(PersonInformationModel o1, PersonInformationModel o2)
	{

	return o1.getName().compareTo(o2.getName());

	}

	}

	
class DataDisplayAdapter extends BaseAdapter{
		
		//scope of global variable should be entire class
		private ArrayList<PersonInformationModel> donorsList;

		public DataDisplayAdapter(ArrayList<PersonInformationModel> list) {
			// scope of local variable should be with in the block;
			donorsList = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return donorsList.size();
		}

		@Override
		public Object getItem(int arg3) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		class ViewHolder {
			
			public TextView name,phno;
		}

		@Override
		public View getView(int position, View v, ViewGroup arg2) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if(v == null){
				holder = new ViewHolder();
				LayoutInflater inflater = getActivity().getLayoutInflater();
				v = inflater.inflate(R.layout.datadisplay, null);
				holder.name = (TextView) v.findViewById(R.id.name);
				holder.phno = (TextView) v.findViewById(R.id.number);
				v.setTag(holder);
				
			}else{
				 holder = (ViewHolder) v.getTag();
			}
			
			
			PersonInformationModel model = donorsList.get(position);
			holder.name.setText(model.getName());
			holder.name.setTextColor(Color.RED);
			holder.phno.setText(model.getPhno());
			holder.phno.setTextColor(Color.GREEN);
			
			return v;
		}
		
	}

@Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
	
	PersonInformationModel model = list.get(position);
	String name =null,phno=null,bloodgroup=null,lastname=null,email=null;
	if(model.getName()!=null){
	 name = model.getName();}
	if(model.getPhno()!=null){
	 phno = model.getPhno();}
	if(model.getBloodGroup() != null){
	bloodgroup = model.getBloodGroup();
	}
	if(model.getLastname() != null){
		lastname = model.getLastname();
		}
	if(model.getEmail() != null){
		email = model.getEmail();
		}
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
	String currentDateandTime = sdf.format(new Date());
	
	Bundle bundle = new Bundle();
	bundle.putString("Name", name);
	bundle.putString("PHNO", phno);
	bundle.putString("BG", bloodgroup);
	bundle.putString("LastName",lastname);
	bundle.putString("Email", email);
	bundle.putString("Date", currentDateandTime);
	bundle.putString("State", model.getState());
	bundle.putString("City", model.getCity());
	
	

	
	
	
	DonorStorage donor = new DonorStorage(getActivity());
	int count = donor.getViewedDonorList().size();
	if(count < 10){
		Log.i("TPT","Size from if  :"+count);
		donor.addRecentViwedDonor(bundle);
	}else{
		Log.i("TPT","Size form else  :"+count);
		donor.deleteOldDonor();
		donor.addRecentViwedDonor(bundle);
	}
	
	
	DonorDetailsFragment detailsFragment = new DonorDetailsFragment();
	detailsFragment.setArguments(bundle);
	FragmentManager fm = getFragmentManager();
	FragmentTransaction ft = fm.beginTransaction();
	ft.replace(R.id.fragment, detailsFragment).addToBackStack(null).commit();
	
	
}




	

}
